//
//  PhotoSelectViewController.swift
//  01图片选择器
//
//  Created by 龚欣 on 15/7/10.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import FFAutoLayout

class PhotoSelectViewController: UIViewController,UICollectionViewDataSource,PhotoSelectCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    var imageArray = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareCollectionView()
    }

    func prepareCollectionView(){
        view.addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.ff_Fill(view)
        collectionView.backgroundColor = UIColor.grayColor()
        collectionView.registerClass(PhotoSelectCell.self, forCellWithReuseIdentifier: photoSelectCellReuseIdentifier)
        flowLayout.itemSize = CGSize(width: 80, height: 80)
        flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count + 1
    }
 
    private let photoSelectCellReuseIdentifier = "photoSelectCellReuseIdentifier"
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoSelectCellReuseIdentifier, forIndexPath: indexPath) as! PhotoSelectCell
        cell.photoCellDelegate = self
        cell.image = indexPath.item == imageArray.count ? nil : imageArray[indexPath.item]
        return cell
    }
    
    func photoSelectButtonDidClick() {
        let pick = UIImagePickerController()
        pick.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        presentViewController(pick, animated: true, completion: nil)
        pick.delegate = self
        
    }
    
    func photoSelectCellDeleteButtonDidCilck(cell: PhotoSelectCell) {
        let indexPath = collectionView.indexPathForCell(cell)
        imageArray.removeAtIndex((indexPath?.item)!)
        collectionView.reloadData()
    }
    
    ///  MARK:·
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageArray.append(image.scaleImage(300))
        dismissViewControllerAnimated(true, completion: nil)
        collectionView.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
   
    
    private lazy var flowLayout = UICollectionViewFlowLayout()
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
}

@objc
protocol PhotoSelectCellDelegate : NSObjectProtocol{
    optional func photoSelectButtonDidClick()
    optional func photoSelectCellDeleteButtonDidCilck(cell : PhotoSelectCell)
}

class PhotoSelectCell : UICollectionViewCell {
    
    weak var photoCellDelegate : PhotoSelectCellDelegate?
    
    var image : UIImage? {
        didSet{
            deleteBtn.hidden = image == nil
            if image == nil {
                photoBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                photoBtn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                return
            }
                photoBtn.setBackgroundImage(image, forState: UIControlState.Normal)
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(photoBtn)
        photoBtn.addTarget(self, action: "photoBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        photoBtn.ff_Fill(self)
        photoBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        addSubview(deleteBtn)
        deleteBtn.ff_AlignInner(ff_AlignType.TopRight, referView: self, size: nil)
        deleteBtn.addTarget(self, action: "photoBtnDelete", forControlEvents: UIControlEvents.TouchUpInside)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func photoBtnClick(){
        
        if image == nil{
            photoCellDelegate?.photoSelectButtonDidClick!()
        }
    }
    
    func photoBtnDelete(){
        photoCellDelegate?.photoSelectCellDeleteButtonDidCilck!(self)
    }
    
    lazy var photoBtn : UIButton = PhotoSelectCell.createButton("compose_pic_add")
    lazy var deleteBtn : UIButton = PhotoSelectCell.createButton("compose_photo_close")
    
    class func createButton(imageName : String) -> UIButton{
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: imageName), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
        return btn
    }
    
}
